package com.gulimall.member.service.impl;

import ch.qos.logback.core.pattern.color.BoldCyanCompositeConverter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.common.to.OAuthResTo;
import com.common.to.UserLoginTo;
import com.common.to.UserRegTo;
import com.common.utils.HttpUtils;
import com.gulimall.member.dao.MemberLevelDao;
import com.gulimall.member.entity.MemberLevelEntity;
import com.gulimall.member.exception.PhoneExistException;
import com.gulimall.member.exception.UserNameExistException;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.gulimall.member.dao.MemberDao;
import com.gulimall.member.entity.MemberEntity;
import com.gulimall.member.service.MemberService;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private MemberLevelDao memberLevelDao;
    @Resource
    private MemberDao memberDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(UserRegTo userRegTo) throws PhoneExistException,UserNameExistException{
        MemberEntity memberEntity = new MemberEntity();
        // 设置手机号（不能重复）
        Integer mobileCount = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", userRegTo.getPhone()));
        if(mobileCount ==null || mobileCount>0){
            throw new PhoneExistException();
        }
        memberEntity.setMobile(userRegTo.getPhone());
        // 设置用户名
        Integer usernameCount = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", userRegTo.getUserName()));
        if(usernameCount == null || usernameCount>0){
            throw new UserNameExistException();
        }
        memberEntity.setNickname(userRegTo.getUserName());
        memberEntity.setUsername(userRegTo.getUserName());
        // 设置密码
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String password = bCryptPasswordEncoder.encode(userRegTo.getPassword());// 加密密码
        memberEntity.setPassword(password);
        setDefaultProperty(memberEntity);
        memberDao.insert(memberEntity);
    }

    private void setDefaultProperty(MemberEntity memberEntity) {
        // 设置默认会员等级
        Integer defaultStatus = memberLevelDao.selectOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1)).getDefaultStatus();
        memberEntity.setLevelId((long)defaultStatus);
        // 设置其他默认值
        memberEntity.setCreateTime(new Date());
        memberEntity.setIntegration(0);
        memberEntity.setGrowth(0);
    }

    @Override
    public MemberEntity login(UserLoginTo userLoginTo) {
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", userLoginTo.getLoginacct()).or().eq("mobile", userLoginTo.getLoginacct()).or().eq("email", userLoginTo.getLoginacct()));
        if(memberEntity == null){
            return null;
        }
        // 检查密码是否正确
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(userLoginTo.getPassword(), memberEntity.getPassword());
        // 如果正确返回对象，不正确返回null
        if(matches){
            return memberEntity;
        }else{
            return null;
        }
    }

    @Override
    public MemberEntity oAuthLogin(OAuthResTo oAuthResTo){
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_id", oAuthResTo.getUid()));
        if(memberEntity == null){
            // 没有注册过
            // 查询基本消息对象
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put("access_token", oAuthResTo.getAccessToken());
            paramMap.put("uid",oAuthResTo.getUid());
            MemberEntity member = null;
            String gender = null;
            try {
                HttpResponse httpResponse = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(),paramMap);
                // 将基本信息各属性设置到要添加对象中
                String jsonString = EntityUtils.toString(httpResponse.getEntity());     // 不能使用JSON来转
                JSONObject jsonObject = JSON.parseObject(jsonString);
                member = new MemberEntity();
                member.setNickname((String) jsonObject.get("name"));
                gender = (String) jsonObject.get("gender");
            } catch (Exception e) {
                e.printStackTrace();
            }
            setDefaultProperty(member);     // 设置默认配置
            BeanUtils.copyProperties(oAuthResTo,member);
            member.setSocialId(oAuthResTo.getUid());
            member.setGender(gender.equals("m")?1:0);
            memberDao.insert(member);
            return member;
        }else {
            // 注册过，将令牌，过期时间修改
            memberEntity.setAccessToken(oAuthResTo.getAccessToken());
            memberEntity.setExpiresIn(oAuthResTo.getExpiresIn());
            memberDao.update(memberEntity,new QueryWrapper<MemberEntity>().eq("social_id",memberEntity.getSocialId()));
            return memberEntity;
        }
    }

}